/*
 * Copyright (c) 2015 DHC Corporation.
 */

package cn.com.dhc.danlu.activity.myself;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.MD5;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.mydl.password.ModifyPasswordRequest;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: LiYongHe
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2015-02-25 13:32<br/>
 *
 * <p>
 * 修改密码画面
 * </p>
 */
public class ChangePasswordActivity extends BaseActivity {

    /**
     * 密码最大长度
     */
    private static final int PASSWORD_MAX_LENGTH = 16;
    /**
     * 密码最小长度
     */
    private static final int PASSWORD_MIN_LENGTH = 6;

    /**
     * 任务类
     */
    // private DanluTaskProxy danluTaskProxy;

    /**
     * 旧密码
     */
    private EditText etOldPassword;

    /**
     * 新密码
     */
    private EditText etNewPassword;

    /**
     * 确认密码
     */
    private EditText etNewPasswordRepeat;

    /**
     * 提交按钮
     */
    private Button btnSave;

    /**
     * 键入密码的长度
     */
    private int length = 0;

    /**
     * 完成提交按钮点击触发事件
     */
    private View.OnClickListener finishOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //            CommonUtils.hideSoftInputFromWindow(delegate.getContext(), btnSave);
            CommonUtils.hideSoftInputFromWindow(ChangePasswordActivity.this, btnSave);
            changePassword();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化界面
        setContentView(R.layout.activity_change_password);
        initView();
        setListener();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    private void changePassword() {
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();
        String newPasswordRepeat = etNewPasswordRepeat.getText().toString().trim();
        // 如果旧密码为空
        if (TextUtils.isEmpty(oldPassword)) {
            ToastUtil.getInstance().show(R.string.change_password_old_write_label);
            return;
        }
        // 如果新密码为空
        if (TextUtils.isEmpty(newPassword)) {
            ToastUtil.getInstance().show(R.string.change_password_new_write_label);
            return;
        }
        // 如果再次输入新密码为空
        if (TextUtils.isEmpty(newPasswordRepeat)) {
            ToastUtil.getInstance().show(R.string.change_password_new_repeat_write);
            return;
        }
        // 如果再次输入密码不一致
        if (!newPassword.equals(newPasswordRepeat)) {
            ToastUtil.getInstance().show(R.string.change_password_nosame_prompt);
            return;
        }
        // 如果老密码和新密码一样
        if (oldPassword.equals(newPassword)) {
            ToastUtil.getInstance().show(R.string.change_password_same_prompt);
            return;
        }
        //新密码规则验证
        if (!CommonUtils.checkNewPasswordRule(newPassword)) {
            ToastUtil.getInstance().show(R.string.change_password_new_rule);
            return;
        }
        //新密码长度判断
        if (newPassword.length() < PASSWORD_MIN_LENGTH || newPassword.length() > PASSWORD_MAX_LENGTH) {
            ToastUtil.getInstance().show(R.string.change_password_new_rule);
            return;
        }
        //        getDelegate().getTaskQueueHandler().get(this).restart();
        // 设置修改密码请求参数
        ModifyPasswordRequest request = new ModifyPasswordRequest();
        request.setOldPassword(MD5.getMD5Str(etOldPassword.getText().toString()));

        request.setNewPassword(MD5.getMD5Str(etNewPassword.getText().toString()));
        request.setToken(agent.getToken());
        // 调用修改密码任务
        agent.getApi().modifyPassword(request).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(ChangePasswordActivity.this, R.string.tips_modify_psw) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        getPreferenceUtils().setPassword(MD5.getMD5Str(etNewPassword.getText().toString()));
                        ToastUtil.getInstance().show(R.string.change_password_succeed_label);
                        ChangePasswordActivity.this.finish();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        return DanluApplication.get().getString(R.string.check_password_is_invalid_error_1301);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    private void initView() {
        etOldPassword = (EditText) findViewById(R.id.edt_password_old); // 输入原密码文本框
        etNewPassword = (EditText) findViewById(R.id.edt_password_new);  // 输入新密码文本框
        etNewPasswordRepeat = (EditText) findViewById(R.id.edt_password_new_repeat);  // 输入确认新密码文本框
        btnSave = (Button) findViewById(R.id.btn_save); // 保存按钮
        llytBack = (LinearLayout) findViewById(R.id.llytBack); // 返回按钮
        btnSave.setClickable(false);
        btnSave.setBackgroundResource(R.drawable.background_btn_unenabled);
    }

    private void setListener() {
        // 设置新密码的文本变化事件监听
        TextWatcher tw = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (etNewPassword.hasFocus()) {
                    if (etNewPasswordRepeat.getText() != null) {
                        length = etNewPasswordRepeat.getText().length();
                    }
                }
                if (etNewPasswordRepeat.hasFocus()) {
                    if (etNewPassword.getText() != null) {
                        length = etNewPassword.getText().length();
                    }
                }
                if (s.length() < PASSWORD_MIN_LENGTH || length < PASSWORD_MIN_LENGTH) {

                    btnSave.setClickable(false);
                    btnSave.setBackgroundResource(R.drawable.background_btn_unenabled);
                } else {
                    if (s.length() >= PASSWORD_MIN_LENGTH && length >= PASSWORD_MIN_LENGTH) {
                        btnSave.setClickable(true);
                        btnSave.setBackgroundResource(R.drawable.selector_button_press);
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };
        etNewPassword.addTextChangedListener(tw);
        etNewPasswordRepeat.addTextChangedListener(tw);
        btnSave.setOnClickListener(finishOnClickListener);
        // 设置键盘事件监听
        etNewPasswordRepeat
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NONE) {
                            changePassword();
                        }
                        return false;
                    }
                });
    }
}